﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Configuration;

namespace Common
{

    public class FileConnect : IDisposable
    {
        #region 私有变量

        private string _fileServer;
        private string _userName;
        private string _password;

        #endregion

        #region win32 API
        [DllImport("advapi32.dll", SetLastError = true)]
        private static extern bool LogonUser(string lpszUsername,
                                             string lpszDomain,
                                             string lpszPassword,
                                             int dwLogonType,
                                             int dwLogonProvider,
                                             ref IntPtr phToken);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern bool CloseHandle(IntPtr handle);

        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public extern static bool DuplicateToken(IntPtr existingTokenHandle,
                                                 int SECURITY_IMPERSONATION_LEVEL,
                                                 ref IntPtr duplicateTokenHandle);


        // logon types
        const int LOGON32_LOGON_INTERACTIVE = 2;
        const int LOGON32_LOGON_NETWORK = 3;
        const int LOGON32_LOGON_NEW_CREDENTIALS = 9;

        // logon providers
        const int LOGON32_PROVIDER_DEFAULT = 0;
        const int LOGON32_PROVIDER_WINNT50 = 3;
        const int LOGON32_PROVIDER_WINNT40 = 2;
        const int LOGON32_PROVIDER_WINNT35 = 1;

        WindowsIdentity newIdentity;
        WindowsImpersonationContext impersonatedUser;
        bool isSuccess = false;
        IntPtr token = IntPtr.Zero;

        public bool IsConnectted
        {
            get { return isSuccess; }
        }

        public FileConnect()
        {
            string fileServer = ConfigurationManager.AppSettings["FileServer"];

            if (!string.IsNullOrEmpty(fileServer))
            {
                isSuccess = Connect(fileServer, ConfigurationManager.AppSettings["FileServerUserName"], ConfigurationManager.AppSettings["FileServerPassword"]);
            }
            else
            {
                isSuccess = true;
            }
        }

        public FileConnect(string fileServer, string userName, string password)
        {
            //string fileServer = ConfigurationManager.AppSettings["FileServer"];
            fileServer = fileServer ?? ConfigurationManager.AppSettings["FileServer"];
            userName = userName ?? ConfigurationManager.AppSettings["FileServerUserName"];
            password = password ?? ConfigurationManager.AppSettings["FileServerPassword"];
            if (!string.IsNullOrEmpty(fileServer))
            {
                this._fileServer = fileServer;
                this._userName = userName;
                this._password = password;
                isSuccess = Connect(this._fileServer, this._userName, this._password);
            }
            else
            {
                isSuccess = true;
            }
        }

        public bool Connect(string remoteAddr, string userName, string password)
        {

            bool isSuccess = LogonUser(userName,
                                              remoteAddr,
                                              password,
                                              LOGON32_LOGON_NEW_CREDENTIALS,
                                              LOGON32_PROVIDER_DEFAULT, ref token);

            newIdentity = new WindowsIdentity(token);
            impersonatedUser = newIdentity.Impersonate();
            return true;
        }

        public void DisConnect()
        {
            if (isSuccess)
            {
                if (impersonatedUser != null)
                    impersonatedUser.Undo();
                if (token != IntPtr.Zero)
                    CloseHandle(token);
            }
        }



        public void Dispose()
        {
            DisConnect();
        }

        #endregion

    }
    public class FileHelper
    {
        public static string ReadFileToString(string path)
        {
            byte[] buffer = ReadFile(path);

            if (buffer == null) return string.Empty;

            return Encoding.UTF8.GetString(buffer);
        }
        public static byte[] ReadFile(string path)
        {
            byte[] result = null;
            if (!File.Exists(path))
                return result;

            try
            {
                using (FileStream fileStream = File.OpenRead(path))
                {
                    result = new byte[fileStream.Length];
                    fileStream.Read(result, 0, result.Length);
                    fileStream.Close();
                }
            }
            catch
            {
                return null;
            }

            return result;
        }
        public static void WriteFile(string path, string data)
        {
            CreateFolder(path);

            byte[] buffer = Encoding.UTF8.GetBytes(data);

            WriteFile(path, buffer);
        }
        public static void WriteFile(string path, byte[] data)
        {
            try
            {
                CreateFolder(path);
                using (FileStream fileStream = File.Create(path))
                {
                    fileStream.Write(data, 0, data.Length);
                    fileStream.Close();
                }
            }
            catch
            {
            }
        }

        public static void CreateFolder(string path)
        {
            string dirPath = path.Substring(0, path.LastIndexOf("\\"));

            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }

        }

    }
}
